public class Solution {
    public static void main(String[] args) {
        String[] strs = {"flower", "flow", "flight"};
        System.out.println(longestCommonPrefix(strs));
    }

    public static String longestCommonPrefix(String[] strs) {
        int l = strs[0].length();
        int j;
        for (int i = 1; i < strs.length; i++) {
            l = Math.min(l, strs[i].length());
            for (j = 0; j < l; j++) {
                if (strs[0].charAt(j) != strs[i].charAt(j))
                    l = j;
            }
            if (l == 0) break;
        }
        return strs[0].substring(0, l);
    }

    public String longestCommonPrefix1(String[] strs) {
        String prefix = strs[0];//默认第一个单词为最长公共前缀
        for (int i = 1; i < strs.length; i++) {
            while (strs[i].indexOf(prefix) != 0) {//只有indexOf=0,才说明是公共前缀
                prefix = prefix.substring(0, prefix.length() - 1);//每次去除末尾的字符
                if (prefix.isEmpty()) {
                    return "";
                }
            }
        }
        return prefix;
    }
}
